<template>
  <div id="menuConfiguration">
    <el-card class="box-card">
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <div>应用管理</div>
        </div>
      </template>
      <!-- 搜索 -->
      <el-row>
        <el-col :span="22">
          <el-input
            v-model="searchData.search"
            style="width: 240px"
            placeholder="请输入..."
            :prefix-icon="Search"
          >
            <template #append>
              <el-button type="primary" size="large" @click="clickSearch"
                >搜索</el-button
              >
            </template>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" size="large" @click="openDialog('add')"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="searchData.tableData"
        style="width: 100%; margin-bottom: 20px"
        border
      >
        <el-table-column prop="id" label="应用ID" width="80px" align="center" />
        <el-table-column
          prop="name"
          label="应用名"
          width="180px"
          align="center"
        />
        <el-table-column prop="img" label="图片" width="80px" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.img"
              style="width: 48px; height: 48px"
              :src="row.img"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="应用类型"
          width="80px"
          align="center"
        >
          <template #default="{ row }">
            {{ row.type == 1 ? '主应用' : '其他' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="is_must"
          label="是否必选"
          width="80px"
          align="center"
        >
          <template #default="{ row }">
            {{ row.is_must == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="blurb"
          label="简介"
          show-overflow-tooltip
          align="center"
        /> -->
        <el-table-column
          prop="produce"
          label="    出品方"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="province"
          label="适用省份"
          width="80px"
          align="center"
        />
        <el-table-column
          prop="targetObj"
          label="    适用年纪"
          width="80px"
          align="center"
        />
        <el-table-column
          prop="price"
          label="年/价格"
          width="80px"
          align="center"
        />
        <el-table-column prop="explain" label="应用简介" align="center">
          <template #default="scope">
            <div
              class="curr"
              style="color: dodgerblue"
              @click="onClickDetail('explain', scope.row.explain)"
            >
              应用简介详情
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="guide" label="使用指导" align="center">
          <template #default="scope">
            <div
              class="curr"
              style="color: dodgerblue"
              @click="onClickDetail('guide', scope.row.guide)"
            >
              使用指导详情
            </div>
          </template>
        </el-table-column>
        <el-table-column label="参数配置" align="center">
          <template #default="scope">
            <div
              class="curr"
              style="color: dodgerblue"
              @click="handleParameter(scope.row)"
            >
              参数配置
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限配置" align="center">
          <template #default="scope">
            <div
              class="curr"
              style="color: dodgerblue"
              @click="permissionConfig(scope.row)"
              v-hasPermi="['customer:appStore:permission']"
            >
              权限配置
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="date"
          label="操作"
          width="200"
          fixed="right"
          align="center"
        >
          <template #default="scope">
            <div class="alitem">
              <div class="icon-button" @click="handleView(scope.row)">
                <el-icon size="16">
                  <SetUp />
                </el-icon>
                查看
              </div>
              <div class="icon-button" @click="handleEdit(scope.row)">
                <el-icon size="16">
                  <EditPen />
                </el-icon>
                <span>编辑</span>
              </div>
              <div class="icon-button" @click="handleDelete(scope.row)">
                <el-icon size="16">
                  <Delete />
                </el-icon>
                <span>删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="right" style="margin-top: 20px" v-if="searchData.total">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="searchData.page"
            v-model:page-size="searchData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="searchData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>
    </el-card>
    <Dialog
      ref="dialogRef"
      width="800px"
      :title="
        dialogVisible === 'add'
          ? '新增应用'
          : dialogVisible === 'view'
            ? '查看应用'
            : '编辑应用'
      "
      size="small"
    >
      <el-form
        ref="ruleFormRef"
        label-position="right"
        label-width="100px"
        :model="managerAppInfo"
        :disabled="dialogVisible === 'view'"
        :rules="rules"
        status-icon
      >
        <el-form-item label="应用名" prop="name">
          <el-input
            v-model="managerAppInfo.name"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="应用类型" prop="type">
          <el-radio-group v-model="managerAppInfo.type">
            <el-radio label="1">主应用</el-radio>
            <el-radio label="2">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否必选" prop="is_must">
          <el-radio-group v-model="managerAppInfo.is_must">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            v-model="managerAppInfo.blurb"
            maxlength="300"
            placeholder="请输入..."
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="出品方">
          <el-input
            v-model="managerAppInfo.produce"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="适用省份">
          <el-input
            v-model="managerAppInfo.province"
            :disabled="true"
            placeholder="全国"
          />
        </el-form-item>
        <el-form-item label="适用年纪">
          <el-select
            v-model="managerAppInfo.targetObj"
            placeholder="请选择适用年纪"
          >
            <el-option
              v-for="option in ageOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年/价格">
          <el-input
            v-model="managerAppInfo.price"
            @input="inputPrice($event)"
          />
        </el-form-item>
        <el-form-item label="购买须知">
          <el-input
            v-model="managerAppInfo.purchaseNotes"
            maxlength="300"
            placeholder="请输入..."
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="应用简介" v-if="dialogVisible !== 'view'">
          <el-scrollbar max-height="200px" v-if="managerAppInfo.explain">
            <p v-html="managerAppInfo.explain" class="rech-text"></p>
          </el-scrollbar>
          <el-button
            v-if="dialogVisible !== 'view'"
            type="primary"
            @click="handleEditRichtext('explain')"
            >编辑</el-button
          >
        </el-form-item>
        <el-form-item label="使用指导" v-if="dialogVisible !== 'view'">
          <el-scrollbar max-height="200px" v-if="managerAppInfo.guide">
            <p v-html="managerAppInfo.guide"></p>
          </el-scrollbar>
          <el-button
            v-if="dialogVisible !== 'view'"
            type="primary"
            @click="handleEditRichtext('guide')"
            >编辑</el-button
          >
        </el-form-item>
        <el-form-item label="图片">
          <ImageUploadNew
            :limit="1"
            :isShowTip="dialogVisible !== 'view' && true"
            :modelValue="imgList"
            @update:modelValue="websmallLog"
          />
        </el-form-item>
        <el-form-item v-if="dialogVisible !== 'view'">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确定</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </Dialog>
    <Dialog
      ref="uEditorPlusgRef"
      width="90%"
      :title="id === 'explain' ? '应用简介' : '使用指导'"
      size="small"
    >
      <UEditorPlus v-model="content" :id="id" :modelValue="content" />

      <el-button type="primary" @click="handleSubmit" style="width: 137px"
        >确定</el-button
      >
    </Dialog>
    <Dialog
      ref="uEditorPlusgViewRef"
      width="90%"
      :appendToBody="true"
      :title="types === 'explain' ? '应用简介' : '使用指导'"
      size="small"
    >
      <p v-html="viewUeditorContent"></p>
    </Dialog>
    <!-- 参数设置 -->
    <Dialog ref="appInfoRef" width="800" title="参数信息">
      <el-button type="primary" class="height40" @click="onClickAddParams"
        >新增参数</el-button
      >
      <el-table :data="tableData" style="width: 100%; margin: 20px 0" border>
        <el-table-column prop="appId" label="应用id" />
        <el-table-column prop="config_vaule" label="参数值" />
        <el-table-column prop="p_type" label="参数类型" />
        <el-table-column prop="remark" label="参数说明" />
        <el-table-column prop="describe" label="使用说明" />
        <el-table-column prop="name" label="展示名称" />
        <el-table-column label="操作">
          <template #default="scope">
            <div class="alitem">
              <div class="icon-button">
                <el-icon size="16" style="cursor: pointer">
                  <EditPen />
                </el-icon>
                <span>编辑</span>
              </div>
              <div class="icon-button" @click="onClickDeleteInfo(scope.row)">
                <el-icon size="16" style="cursor: pointer">
                  <Delete />
                </el-icon>
                <span>删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </Dialog>
    <Dialog ref="addAppInfoRef" width="800" title="参数信息">
      <el-form
        ref="ruleFormRef"
        :model="formInfo"
        label-width="auto"
        :rules="addAppInfoRules"
        status-icon
      >
        <el-form-item label="应用id" prop="appId">
          <el-input
            v-model="formInfo.appId"
            placeholder="请输入应用id"
            clearable
          />
        </el-form-item>
        <el-form-item label="展示名称" prop="name">
          <el-input
            v-model="formInfo.name"
            placeholder="请输入展示名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="参数值" prop="config_vaule">
          <el-input
            v-model="formInfo.config_vaule"
            placeholder="请输入参数值"
            clearable
          />
        </el-form-item>
        <el-form-item label="参数类型" prop="p_type">
          <el-select
            v-model="formInfo.p_type"
            placeholder="请选择参数类型"
            size="large"
            style="width: 150px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数说明" prop="remark">
          <el-input
            v-model="formInfo.remark"
            placeholder="请输入参数说明"
            clearable
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="describe">
          <el-input
            v-model="formInfo.describe"
            placeholder="请输入使用说明"
            clearable
          />
        </el-form-item>
      </el-form>
      <el-divider />
      <div class="right">
        <el-button class="height40" @click="closeChange">取消</el-button>
        <el-button type="primary" class="height40" @click="submitAppInfo"
          >提交</el-button
        >
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

import {
  getAppList,
  newAppInfo,
  getAppInfo,
  delApp,
  getManagerAppList,
} from '@/api/appv2/appv2'; //  getProvinceInfo,
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { useRouter } from 'vue-router';
const router = useRouter();

const searchData = ref({
  page: 1,
  pageSize: 10,
  search: '',
  tableData: [],
  total: 0,
});

const ageOptions = [
  { value: '全年级', label: '全年级' },
  { value: '初中', label: '初中' },
  { value: '高中', label: '高中' },
];

// 获取列表
const getList = () => {
  const { page, pageSize, search } = searchData.value;
  getAppList({ page, pageSize, search }).then(({ data }) => {
    if (data) {
      searchData.value.tableData = data.data;
      searchData.value.page = data.current_page;
      searchData.value.pageSize = data.per_page;
      searchData.value.total = data.total;
    }
  });
};
getList();

// 搜索
const clickSearch = () => {
  getList();
};
// 分页
const handleSizeChange = (val) => {
  searchData.value.pageSize = val;
  getList();
};
const handleCurrentChange = (val) => {
  searchData.value.page = val;
  getList();
};

const types = ref('');
const uEditorPlusgViewRef = ref('');
const viewUeditorContent = ref('');
const onClickDetail = (type, data) => {
  types.value = type;
  viewUeditorContent.value = data;
  uEditorPlusgViewRef.value.openChange();
};

// 操作栏
const getAppInfoReq = ({ id }, type) => {
  getAppInfo({ id }).then(({ data }) => {
    if (data) {
      openDialog(type);
      managerAppInfo.value = data;
      imgList.value = data.img ? [data.img] : [];
    }
  });
};
const handleView = (data) => {
  getAppInfoReq(data, 'view');
};
const handleEdit = (data) => {
  getAppInfoReq(data, 'edit');
};
// 删除
const handleDelete = ({ id }) => {
  delApp({ id }).then(({ code, msg }) => {
    if (code == 20000) {
      ElMessage({
        message: msg,
        type: 'success',
      });
    }
    if (searchData.value.page > 1 && searchData.value.tableData.length === 1)
      searchData.value.page--;
    getList();
  });
};
// 参数配置
const appInfoRef = ref('');
const addAppInfoRef = ref('');
const appId = ref(0);
const tableData = ref([]);
const formInfo = ref({
  id: '0', //    0为新增，其他为修改
  remark: '', //参数说明
  config_vaule: '', //参数值
  p_type: '', //参数类型：1 数字，2 字符串，3 json
  describe: '', //    使用说明
  name: '', //    展示名称
  appId: '', //    应用id
});
// 获取列表
const getAppListS = (id) => {
  getManagerAppList({ appId: id }).then(({ data }) => {
    tableData.value = data;
  });
};
const handleParameter = ({ id }) => {
  appId.value = id;
  getAppListS(id);
  appInfoRef.value.openChange();
};
const permissionConfig = (val) => {
  router.push({ path: '/customer/permissionConfig', query: { id: val.id } });
};
const onClickAddParams = () => {
  addAppInfoRef.value.openChange();
};
const onClickDeleteInfo = () => {
  ElMessage.success('删除成功');
};
const typeOptions = [
  {
    value: '1',
    label: '数字',
  },
  {
    value: '2',
    label: '字符串',
  },
  {
    value: '3',
    label: 'json',
  },
];
const addAppInfoRules = {
  remark: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入参数说明',
    },
  ],
  config_vaule: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入参数值',
    },
  ],
  p_type: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择参数类型',
    },
  ],
  describe: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入使用说明',
    },
  ],
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入展示名称',
    },
  ],
  appId: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入应用id',
    },
  ],
};

// 提交
const submitAppInfo = () => {};
// 取消
const closeChange = () => {};

// 弹框
import Dialog from '@/components/Dialog/Dialog.vue';
const dialogRef = ref();
const dialogVisible = ref('add');
const managerAppInfo = ref({
  id: 0, //0 新增，其他修改
  name: '', //应用名
  type: '1', //1主应用；2其他
  is_must: '1', //1 ，必选，0 否
  blurb: '', //简介
  produce: '', //出品方
  province: '全国', //    适用省份
  targetObj: '', //    适用年纪
  price: '', //    年/价格
  explain: '', //    应用简介
  guide: '', //    使用指导
  img: '', //
  purchaseNotes: '', //购买须知
});
const rules = reactive({
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请填写应用名称',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择应用类型',
      trigger: 'change',
    },
  ],
  is_must: [
    {
      required: true,
      message: '请选择是否必填',
      trigger: 'change',
    },
  ],
});

// 添加弹框
const openDialog = (type) => {
  dialogVisible.value = type;
  imgList.value = [];
  managerAppInfo.value = {
    id: 0, //0 新增，其他修改
    name: '', //应用名
    type: '1', //1主应用；2其他
    is_must: '1', //1 ，必选，0 否
    blurb: '', //简介
    produce: '', //出品方
    province: '全国', //    适用省份
    targetObj: '全年级', //    适用年纪
    price: '', //    年/价格
    explain: '', //    应用简介
    guide: '', //    使用指导
    img: '', //
  };
  dialogRef.value.openChange();
};

// 上传图片
const imgList = ref([]);
const websmallLog = (val) => {
  managerAppInfo.value.img = val ? val : '';
  imgList.value = val ? [val] : [];
};

//价格-格式
const inputPrice = (v) => {
  let formatValue =
    ('' + v) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
      .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
      .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
      .match(/^\d*(\.?\d{0,2})/g)[0] || ''; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
  managerAppInfo.value.price = formatValue;
};

const uEditorPlusgRef = ref();
const id = ref('');
const content = ref('');
const handleEditRichtext = (type) => {
  id.value = type;
  content.value =
    id.value == 'explain'
      ? managerAppInfo.value.explain
      : managerAppInfo.value.guide;
  uEditorPlusgRef.value.openChange();
};
const handleSubmit = () => {
  id.value == 'explain'
    ? (managerAppInfo.value.explain = content.value)
    : (managerAppInfo.value.guide = content.value);
  id.value = '';
  content.value = '';
  uEditorPlusgRef.value.closeChange();
};

const ruleFormRef = ref();
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      newAppInfo(managerAppInfo.value).then(() => {
        dialogRef.value.closeChange();
        getList();
      });
    }
  });
};
// 弹框取消
const resetForm = (formEl) => {
  formEl.resetFields();
  dialogRef.value.closeChange();
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

::v-deep(.el-row) {
  margin: 10px 0 20px;
}

::v-deep(.el-upload--picture-card) {
  width: 70px;
  height: 70px;
}

::v-deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 70px;
  height: 70px;
}

.alitem {
  .icon-button {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 10px;
    cursor: pointer;
  }
}

::v-deep(.el-scrollbar) {
  height: 92%;
}

::v-deep(.el-overlay) {
  z-index: 1001 !important;
}

.over-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</style>
